<template>
  <div class="course-section">
    <el-card
        v-loading="isloading"
      ><el-tree
        :data="data"
        :props="defaultProps"
        draggable
        :allow-drop="handleAllowDrop"
        @node-drop="handleNodeDrop"
      >
        <div class="inner" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span v-if="data.sectionName" class="actions">
            <el-button>编辑</el-button>
            <el-button>添加课时</el-button>
            <el-button>状态</el-button>
          </span>
          <span v-else class="actions">
            <el-button>编辑</el-button>
            <el-button @click="$router.push({
                name: 'video',
                params: {
                  courseId
                },
                query: {
                  lessonId: data.id
                }
              })">上传视频</el-button>
            <el-button>状态</el-button>
          </span>
        </div></el-tree
      ></el-card
    >
  </div>
</template>

<script>
import { getTreeList, updatelist, savelist } from '@/services/section'

export default {
  name: 'courseSection',
  props: {
    courseId: {
      type: [Number, String],
      require: true
    }
  },
  data () {
    return {
      data: [],
      defaultProps: {
        children: 'lessonDTOS',
        label (data) {
          return data.sectionName || data.theme
        }
      },
      isloading: false
    }
  },
  created () {
    this.getList()
  },
  methods: {
    async getList () {
      const { data } = await getTreeList(this.courseId)
      if (data.code === '000000') {
        this.data = data.data
      }
    },
    handleAllowDrop (drogingNode, dropNode, type) {
      return (
        type !== 'inner' && drogingNode.data.sectionId === dropNode.data.sectionId
      )
    },
    async handleNodeDrop (drogingNode, dropNode, type, event) {
      this.isloading = true
      try {
        await Promise.all(
          dropNode.parent.childNodes.map((item, index) => {
            if (drogingNode.data.sectionId) {
              return savelist({
                id: item.data.id,
                orderNum: index
              })
            } else {
              return updatelist({
                id: item.data.id,
                orderNum: index
              })
            }
          })
        )
        this.isloading = false
        this.$message.success('数据更新成功')
      } catch (err) {
        this.$message.error('数据更新失败')
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.inner {
  display: flex;
  flex: 1;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
::v-deep .el-tree-node__content {
  height: auto;
}
</style>
